package com.yn.iotxiao.controller.User;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yn.iotxiao.Utils.JsonHelper;
import com.yn.iotxiao.Utils.SecretUtil;
import com.yn.iotxiao.authorize.Authorize;
import com.yn.iotxiao.request.PageRequest;
import com.yn.iotxiao.response.ResponseResult;
import com.yn.iotxiao.sql.entity.User.StudentInfo;
import com.yn.iotxiao.sql.entity.User.TeacherInfo;
import com.yn.iotxiao.sql.entity.User.User;
import com.yn.iotxiao.sql.services.User.StudentService;
import com.yn.iotxiao.sql.services.User.TeacherService;
import com.yn.iotxiao.sql.services.UserService;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RequestMapping("/student")
@Slf4j
@RestController
@ResponseResult
public class StudentController {

    @Autowired
    StudentService service;

    @Autowired
    UserService uService;

    @PutMapping
    @Authorize
    public Object putStudent(@Validated @RequestBody StudentInfo request) throws Exception {

        var user = uService.getWithUid(request.getGh());

        if (user != null && !"student".equals(user.getType())) {
            throw new Exception("当前工号用户已经存在且不是学生用户，请检查");
        }
        String loginId = request.getGh();
        int result = uService.insert(new User(request.getGh(),request.getName(),loginId,loginId,
                SecretUtil.md5(loginId),"student",false));
        if (result < 0) {
            throw new Exception("写入用户失败");
        }
         result = service.insert(request);
        if (result > 0) {
            return  "保存成功";
        }
        throw new Exception("保存失败");
    }

    @PostMapping("/list")
    @Authorize
    public Object getList(@RequestBody PageRequest request) {

        List<StudentInfo> list = service.getListPage(request.getSearchKey(),request.getPage(),request.getPageSize());
        int total = service.getTotal(request.getSearchKey());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list",list);
        jsonObject.put("total",total);
        return  jsonObject;
    }

    @DeleteMapping("/{gh}")
    @Authorize
    public String deleteWithGh(@PathVariable String gh) throws Exception{
        int result = service.deleteWithKey(gh);
        if (result > 0) {
            uService.delete(gh);
            return "删除成功";
        }
        throw new Exception("删除失败");
    }

    @PutMapping("/list")
    @Authorize
    public Object putList(@RequestBody List<JSONObject> list) throws Exception{
        if (list == null || list.size() == 0) {
            throw new Exception("未获取到数据");
        }

        List<StudentInfo> inserts = new ArrayList<>();
        JSONArray error = new JSONArray();
        JSONArray success = new JSONArray();
        List<User> users = new ArrayList<>();
        for (JSONObject data : list) {
            String name = JsonHelper.getValue(data, "姓名");
            if (name.isEmpty()) {
                data.put("mark", "姓名为空");
                error.add(data);
                continue;
            }
            String gh = JsonHelper.getValue(data, "学籍号");
            if (gh.isEmpty()) {
                data.put("mark", "学籍号为空");
                error.add(data);
                continue;
            }

            String typeStr =JsonHelper.getValue (data, "住校/走读");
            int type = 0;
            if (!StringUtils.isBlank(typeStr)) {
                if (typeStr.equals("住校")) {
                    type = 1;
                }else if (typeStr.equals("走读")) {
                    type = 2;
                }
            }

            //筛选是否已经录入过
            User user = uService.getWithUid(gh);
            if (user != null && StringUtils.isBlank(user.getUid())) {
                data.put("mark", "已经录入过了");
                error.add(data);
                continue;
            }


            data.put("mark", "录入成功");
            success.add(data);
            //其他的数据写入
            StudentInfo studentInfo = new StudentInfo();
            studentInfo.setName(name);
            studentInfo.setGh(gh);
            studentInfo.setLivingType(type);


            inserts.add(studentInfo);
            String loginId = gh;
            users.add(new User(gh,name,loginId,loginId,
                    SecretUtil.md5(loginId),"student",false));
        }
        log.info("inserts:" + inserts.size());

        if (inserts.size() > 0) {
            uService.batchInsert(users);
            service.batchInsert(inserts);
        }

        JSONObject data = new JSONObject();
        data.put("list", list);
        data.put("success", success);
        data.put("error", error);
        return data;
    }
}
